<?php
declare (strict_types=1);

namespace app\backend\controller\v2;

use app\backend\validate\CateValidate;
use app\backend\validate\QuestionValidate;
use app\common\model\Cate as CateModel;
use app\common\model\Question as QuestionModel;
use app\common\model\Cate;
use think\exception\ValidateException;
use think\Request;

class Question extends BaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $type = input('type', 3);
        $page = input('page/d', 1);
        $size = 10;
        //获取分类id
        $cate_id = CateModel::where('type', $type)->column('id');
        $where = [
            ['status', '=', 1],
            ['cate_id', 'in', $cate_id]
        ];
        $model = QuestionModel::where($where);
        //获取该分类下的数据
        $data = $model->with(['getMember', 'getCate'])
            ->withAttr('image', function ($val, $a) {
                return env('app.yuming') . $val;
            })
            ->withAttr('picture', function ($val2, $a2) {
                return env('app.yuming') . $val2;
            })
            ->order('id desc')
            ->page($page, $size)
            ->select();
        //统计数量
        $rows = $model->count();
        $maxPage = ceil($rows / $size);
        foreach ($data as &$v) {
            if (empty($v->getMember)) {
                $v['member_id'] = "暂无用户名";
                $v['cate_id'] = $v->getCate->name;
                unset($v->getCate);
            } else {
                $v['member_id'] = $v->getMember->account;
                unset($v->getMember);
                $v['cate_id'] = $v->getCate->name;
                unset($v->getCate);
            }
        }
        return sucessMsg(200, '获取成功！', ['data' => $data, 'page' => $page, 'maxPage' => $maxPage, 'rows' => $rows]);
    }

    /**
     * 保存新建的资源
     *
     * @param \think\Request $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $postData = input('post.');
        $postData['member_id'] = $this->user_id;
        try {
            //  验证参数
            validate(QuestionValidate::class)->scene('save')->check($postData);
            $model = new QuestionModel();
            if ($model->save($postData)) return sucessMsg(200, '添加成功');
            return sucessMsg(422, '添加失败');
        } catch (ValidateException $e) {
            return errMsg(400, $e->getError());
        }
    }

    /**
     * 显示编辑资源表单页.
     *
     * @return \think\Response
     */
    public function edit()
    {
        $id = input('get.id/d');
        $model = new QuestionModel();
        if (empty($id))
            return errMsg(422, 'id不能为空');
        $data = $model->where('id', $id)->find();
        $data['picture'] = env('app.yuming') . $data['picture'];
        $data['image'] = env('app.yuming') . $data['image'];
        $type = Cate::where('id', $data['cate_id'])->column('type');
        $datas = getList(Cate::where(['status' => 1, 'type' => $type[0]])->field('id,name,pid')->select()->toArray());
        if (empty($data))
            return errMsg(422, '无效id');
        return sucessMsg(200, '获取成功！', ['data' => $data, 'cate' => $datas]);
    }

    /**
     * 保存更新的资源
     *
     * @param \think\Request $request
     * @param int $id
     * @return \think\Response
     */
    public function update(Request $request)
    {
        $postData = input('post.');
        try {
            //  验证参数
            validate(QuestionValidate::class)->scene('update')->check($postData);
            if (strpos($postData['picture'], '.com') !== false) {
                $postData['picture'] = substr($postData['picture'], strpos($postData['picture'], "m") + 2);
            }
            if (strpos($postData['image'], '.com') !== false) {
                $postData['image'] = substr($postData['image'], strpos($postData['image'], "m") + 2);
            }
            $model = new QuestionModel();
            $cate = $model->where('id', $postData['id'])->find();
            if ($cate->save($postData)) return sucessMsg(200, '修改成功');
            return sucessMsg(422, '修改失败');
        } catch (ValidateException $e) {
            return errMsg(400, $e->getError());
        }
    }

    /**
     * 删除指定资源
     *
     * @return \think\Response
     */
    public function delete()
    {
        $model = new QuestionModel();
        $id = input('id/d', 0);
        if (empty($id)) {
            return errMsg(422, 'id不能为空');
        }
        $data = $model->where('id', $id)->find();
        if (empty($data))
            return errMsg(422, '无效id');
        if ($model->destroy($id)) {
            return sucessMsg(200, '删除成功！');
        }
        return errMsg(422, '删除失败');
    }

    //获取分类列表
    public function indexcate()
    {
        $page = input('page/d', 1);
        $size = 10;
        $where = [
            ['status', '=', 1],
            ['type', '=', 3]
        ];
        $model = CateModel::where($where);
        $rows = $model->count();
        $maxPage = ceil($rows / $size);
        $datas = $model->order('id desc')
            ->page($page, $size)
            ->select()
            ->toArray();
        return sucessMsg(200, '获取成功！', ['data' => $datas, 'page' => $page, 'maxPage' => $maxPage, 'rows' => $rows]);
    }

    //获取所有分类
    public function createcate()
    {
        //type == 3   --->(问答)
        $type = env('app.wenda');
        $datas = getList(Cate::where(['status' => 1, 'type' => $type])->field('id,name,pid')->select()->toArray());
        return sucessMsg(200, '获取成功！', $datas);
    }

    //添加分类
    public function savecate(Request $request)
    {
        //添加分类
        $postData = input();
        try {
            //  验证参数
            validate(CateValidate::class)->scene('save')->check($postData);
            $model = new CateModel();
            $postData['type'] = 3;
            if ($model->save($postData)) return sucessMsg(200, '添加成功');
            return sucessMsg(422, '添加失败');
        } catch (ValidateException $e) {
            return errMsg(400, $e->getError());
        }
    }

    //编辑分类
    public function editcate()
    {
        //修改
        $postData = input('post.');
        try {
            //  验证参数
            validate(CateValidate::class)->scene('update')->check($postData);
            $model = new CateModel();
            $cate = $model->where('id', $postData['id'])->find();
            if ($cate->save($postData)) return sucessMsg(200, '修改成功');
            return sucessMsg(422, '修改失败');
        } catch (ValidateException $e) {
            return errMsg(400, $e->getError());
        }
    }

    //删除分类
    public function deletecate()
    {
        $id = input('id/d');
        if (empty($id)) {
            return errMsg(422, 'id不能为空');
        }
        $data = CateModel::where('id', $id)->find();
        if (empty($data))
            return errMsg(422, '无效id');
        $child = CateModel::where(['pid' => $id])->select()->toArray();
        if (!empty($child)) {
            return errMsg(400, '含有子类,无法删除');
        } else {
            if (CateModel::destroy($id))
                return sucessMsg(200, '删除成功!');
        }
        return errMsg(422, '删除失败');
    }
}
